<?php
/**
 * Description: 对账相关模型
 * User: wuhao
 * Date: 2017-07-19
 * Time: 10:49
 */
namespace app\backend\model;

use think\Model;

class Reconciliation extends Model
{
    private $_thisTable = 'z_reconciliation';
    private $_result    = 'z_reconciliation_result';

    /**
     * @comment 批量插入数据
     * @author wuhao
     * @param $data array 插入的数据
     * @return bool
     */
    public function addAll($data)
    {
        if (!$data || !is_array($data)) {
            return false;
        }
        return $this->table($this->_thisTable)->insertAll($data);
    }

    /**
     * @comment 获取对账记录
     * @author wuhao
     * @param array  $where  条件
     * @param string $field  参数
     */
    public function getList($where, $field = '*')
    {
        return $this->table($this->_thisTable)->field($field)->where($where)->select();
    }

    /**
     * @comment  新增对账结果
     * @author wuhao
     * @param $source
     * @param $type
     * @param $date
     * @param $amount
     * @param $record
     * @param $result
     * @param $count
     * @param $url
     */
    public function addResult($source, $type, $date, $amount, $record, $result, $count, $url)
    {
        $data = [
            'source' => $source,
            'type'   => $type,
            'date'   => $date,
            'amount' => $amount,
            'record' => $record,
            'result' => $result,
            'count'  => $count,
            'url'    => $url,
        ];
        return $this->table($this->_result)->insertGetId($data);
    }

    /**
     * @comment 获取对账文件结果
     * @author wuhao
     * @param $begin
     * @param $end
     * @param $source
     * @param $type
     * @param $result
     * @param $page
     * @param $pageSize
     */
    public function getResult($begin, $end, $source, $type, $result, $page, $pageSize)
    {
        $where = [];
        if ($begin && $end) {
            $where['date'] = ['between', [$begin, $end]];
        }

        if ($source != -1) {
            $where['source'] = $source;
        }
       
        if ($type != -1) {
            $where['type'] = $type;
        }
        if ($result != -1) {
            $where['result'] = $result;
        }
        $res = $this->table($this->_result)->where($where)->page($page, $pageSize)->order('id desc')->select();
        if (!$res) {
            return [];
        } else {
            $sum = $this->table($this->_result)->where($where)->count();
            $total = ceil($sum / $pageSize);
            return [
                'total' => $total,
                'list' => $res,
            ];
        }
    }

    /**
     * @comment 获取对账文件结果地址
     * @author wuhao
     * @param $id
     * @return mixed
     */
    public function getResultUrl($id)
    {
        $res = $this->table($this->_result)->field('url')->where(['id' => $id])->find();
        return $res;
    }
}